import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { buildTree } from '@/utils/tree'
import type { TreeNode, Device } from '@/types'
import { getCameraTree } from '@/api/camera'
import { $getDeviceList } from '@/api/device'
import { $getAllServer, $getStreamPreviewPort } from '@/api/nvr'
import { 
  generatePlaybackToken, 
  getPlaybackStreamId,
  setPlaybackStreamServers,
  controlPlayback
} from '@/api/playback'
import type { StreamServer } from '@/types'

// 录像记录类型定义
export interface PlaybackRecord {
  id: string
  cameraId: string
  cameraName: string
  startTime: string
  endTime: string
  duration: number // 秒
  fileSize: number // 字节
  type: 'schedule' | 'manual' | 'alarm'
  playUrl: string
  thumbnail: string
  status: 'normal' | 'error' | 'downloading'
}

// 查询条件类型定义
export interface PlaybackQuery {
  dateRange: [string, string]
  recordType: 'all' | 'schedule' | 'manual' | 'alarm'
}

// 分页配置类型定义
export interface PlaybackPagination {
  currentPage: number
  pageSize: number
  total: number
}

export const usePlaybackStore = defineStore('playback', () => {
  // 状态
  const loading = ref(false)
  const selectedRecord = ref<PlaybackRecord | null>(null)
  const playbackPosition = ref(0)
  const isPlaying = ref(false)
  
  // 流媒体服务器
  const streamServer = ref<StreamServer[]>([])
  const streamPort = ref<string>('')
  const streamPlaybackPort = ref<string>('')
  // 目录树相关
  const menuTree = ref<TreeNode[]>([])
  const selectedNode = ref<TreeNode | null>(null)
  const defaultExpandedKeys = ref<number[]>([])
  
  // 摄像头列表
  const cameraList = ref<Device[]>([])
  const selectedCamera = ref<Device | null>(null)
  
  // 存储每个文件夹的摄像头列表 - 移到store中保持状态
  const folderCameraMap = ref<Map<number, Device[]>>(new Map())
  
  // 摄像机分页配置
  const cameraPagination = reactive<PlaybackPagination>({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })
  
  // 查询条件
  const queryForm = reactive<PlaybackQuery>({
    dateRange: ['', ''],
    recordType: 'all'
  })
  
  // 分页配置
  const pagination = reactive<PlaybackPagination>({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })
  
  // 数据列表
  const recordList = ref<PlaybackRecord[]>([])
  
  // 录像查询结果存储
  const playbackRecords = ref<any[]>([])
  
  // 流地址相关状态
  const currentStreamUrls = ref<Map<string, string>>(new Map()) // 存储每个摄像头的流地址
  const isLoadingStream = ref(false)
  const streamError = ref<string>('')
  
  // 当前播放控制相关状态
  const currentPlaybackToken = ref<string>('')
  const currentStreamId = ref<string>('')
  const currentStreamUrl = ref<string>('')
  
  // 加载菜单树
  const loadMenuTree = async () => {
    try {
      loading.value = true
      const streamPortResponse = await $getStreamPreviewPort()
      console.log('流端口API响应:', streamPortResponse)
      console.log('recordStreamPort:', streamPortResponse.data.recordStreamPort)
      console.log('realStreamPort:', streamPortResponse.data.realStreamPort)
      
      streamPort.value = streamPortResponse.data.recordStreamPort
      streamPlaybackPort.value = streamPortResponse.data.realStreamPort
      const streamServerResponse = await $getAllServer()
      streamServer.value = streamServerResponse.data || []
      const response = await getCameraTree()
      if (response.data && Array.isArray(response.data)) {
        // 使用项目中的树形数据转换方法
        menuTree.value = buildTree(response.data,0,true) // 隐藏空目录
        
        // 默认选中第一个根节点，并自动加载其摄像头数据
        if (menuTree.value.length > 0) {
          selectedNode.value = menuTree.value[0]
          // 设置默认展开的节点（根节点）
          defaultExpandedKeys.value = [menuTree.value[0].id]
          // 自动加载第一个根节点的摄像头列表
          await loadCameraList(menuTree.value[0].id)
        }
      }
    } finally {
      loading.value = false
    }
  }
  
  // 生成录像记录假数据（暂时保留，因为录像接口可能还未实现）
  const generateMockRecords = () => {
    const mockRecords: PlaybackRecord[] = []
    const recordTypes: Array<'schedule' | 'manual' | 'alarm'> = ['schedule', 'manual', 'alarm']
    
    for (let i = 1; i <= 50; i++) {
      const camera = cameraList.value[Math.floor(Math.random() * cameraList.value.length)]
      if (camera) {
        const startTime = new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000)
        const duration = Math.floor(Math.random() * 3600) + 300 // 5分钟到1小时
        const endTime = new Date(startTime.getTime() + duration * 1000)
        
        mockRecords.push({
          id: `record_${i}`,
          cameraId: camera.id.toString(),
          cameraName: camera.name,
          startTime: startTime.toISOString().slice(0, 19).replace('T', ' '),
          endTime: endTime.toISOString().slice(0, 19).replace('T', ' '),
          duration,
          fileSize: Math.floor(Math.random() * 1000 * 1024 * 1024) + 100 * 1024 * 1024, // 100MB到1GB
          type: recordTypes[Math.floor(Math.random() * recordTypes.length)],
          playUrl: `rtmp://mock-server.com/playback/${i}`,
          thumbnail: `https://picsum.photos/160/90?random=${i}`,
          status: 'normal'
        })
      }
    }
    
    recordList.value = mockRecords.sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime())
    pagination.total = mockRecords.length
  }
  
  // 加载摄像头列表
  const loadCameraList = async (menuId?: number, page: number = 1, pageSize: number = 20) => {
    if (!menuId) return []
    
    try {
      loading.value = true
      // 使用正确的API获取文件夹下的摄像机
      const response = await $getDeviceList(menuId.toString(),false) // isGetALL=true 获取所有子文件夹的设备
      
      if (response.data && Array.isArray(response.data)) {
        const devices = response.data || []
        const total = devices.length
        
        // 更新全局摄像头列表
        cameraList.value = devices
        // 更新分页信息
        cameraPagination.currentPage = page
        cameraPagination.pageSize = pageSize
        cameraPagination.total = total
        
        // 将摄像头数据存储到folderCameraMap中
        folderCameraMap.value.set(menuId, devices)
        console.log('Store: Loaded cameras for folder', menuId, ':', devices.length, 'devices')
        
        return devices
      }
      return []
    } finally {
      loading.value = false
    }
  }
  
  // 加载摄像头录像记录
  const loadCameraRecords = async (cameraId: string) => {
    loading.value = true
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 根据摄像头ID和查询条件过滤数据
      let filteredRecords = recordList.value.filter(record => record.cameraId === cameraId)
      
      if (queryForm.recordType !== 'all') {
        filteredRecords = filteredRecords.filter(record => record.type === queryForm.recordType)
      }
      
      if (queryForm.dateRange[0] && queryForm.dateRange[1]) {
        const startDate = new Date(queryForm.dateRange[0])
        const endDate = new Date(queryForm.dateRange[1])
        filteredRecords = filteredRecords.filter(record => {
          const recordDate = new Date(record.startTime)
          return recordDate >= startDate && recordDate <= endDate
        })
      }
      
      // 更新分页
      pagination.total = filteredRecords.length
      pagination.currentPage = 1
      
      return filteredRecords
    } finally {
      loading.value = false
    }
  }
  
  // 选择录像记录
  const selectRecord = (record: PlaybackRecord) => {
    selectedRecord.value = record
    playbackPosition.value = 0
    isPlaying.value = false
  }
  
  // 播放录像
  const playRecord = (record: PlaybackRecord) => {
    selectedRecord.value = record
    isPlaying.value = true
    playbackPosition.value = 0
  }
  
  // 暂停播放
  const pausePlayback = async () => {
    if (currentPlaybackToken.value && currentStreamId.value) {
      try {
        const result = await controlPlayback(
          currentPlaybackToken.value,
          currentStreamId.value,
          'pause'
        )
        if (result.success) {
          isPlaying.value = false
          console.log('暂停播放成功')
        } else {
          console.error('暂停播放失败:', result.msg)
        }
      } catch (error) {
        console.error('暂停播放出错:', error)
      }
    } else {
      isPlaying.value = false
    }
  }
  
  // 继续播放
  const resumePlayback = async () => {
    if (currentPlaybackToken.value && currentStreamId.value) {
      try {
        const result = await controlPlayback(
          currentPlaybackToken.value,
          currentStreamId.value,
          'play'
        )
        if (result.success) {
          isPlaying.value = true
          console.log('恢复播放成功')
        } else {
          console.error('恢复播放失败:', result.msg)
        }
      } catch (error) {
        console.error('恢复播放出错:', error)
      }
    } else {
      isPlaying.value = true
    }
  }
  
  // 跳转到指定位置
  const seekToPosition = async (position: number, targetTime?: string) => {
    playbackPosition.value = position
    
    if (currentPlaybackToken.value && currentStreamId.value && targetTime) {
      try {
        const result = await controlPlayback(
          currentPlaybackToken.value,
          currentStreamId.value,
          'seek',
          targetTime
        )
        if (result.success) {
          console.log('跳转播放成功')
        } else {
          console.error('跳转播放失败:', result.msg)
        }
      } catch (error) {
        console.error('跳转播放出错:', error)
      }
    }
  }
  
  // 处理树节点点击
  const handleNodeClick = (node: TreeNode) => {
    selectedNode.value = node
    selectedCamera.value = null
    selectedRecord.value = null
    pagination.currentPage = 1
  }
  
  // 选择摄像头
  const selectCamera = (camera: Device) => {
    selectedCamera.value = camera
    selectedRecord.value = null
    pagination.currentPage = 1
  }
  
  // 重置查询条件
  const resetQuery = () => {
    queryForm.dateRange = ['', '']
    queryForm.recordType = 'all'
    selectedRecord.value = null
    pagination.currentPage = 1
  }
  
  // 分页处理
  const handlePageChange = (page: number) => {
    pagination.currentPage = page
  }

  const handlePageSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.currentPage = 1
  }
  
  // 摄像机分页处理
  const handleCameraPageChange = async (page: number) => {
    if (selectedNode.value) {
      await loadCameraList(selectedNode.value.id, page, cameraPagination.pageSize)
    }
  }

  const handleCameraPageSizeChange = async (size: number) => {
    if (selectedNode.value) {
      await loadCameraList(selectedNode.value.id, 1, size)
    }
  }
  
  // 下载录像
  const downloadRecord = async (record: PlaybackRecord) => {
    // 模拟下载
    record.status = 'downloading'
    await new Promise(resolve => setTimeout(resolve, 2000))
    record.status = 'normal'
  }
  
  // 导出录像列表
  const exportRecords = async () => {
    // 模拟导出
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
  
  // 设置录像查询结果
  const setPlaybackRecords = (records: any[]) => {
    playbackRecords.value = records
  }
  
  // 生成回放流地址
  const generatePlaybackStreamUrl = async (
    camera: Device, 
    selectedDate: string, 
    selectedTime: string
  ): Promise<string> => {
    try {
      isLoadingStream.value = true
      streamError.value = ''
      
      // 检查必要参数
      if (!selectedDate || !selectedTime) {
        throw new Error('请选择日期和时间')
      }
      
      // 设置流媒体服务器
      if (streamServer.value.length > 0) {
        setPlaybackStreamServers(streamServer.value, streamPort.value)
      }
      
      // 构建开始和结束时间
      const date = new Date(selectedDate)
      const [hours, minutes, seconds] = selectedTime.split(':').map(Number)
      
      // 设置开始时间为选择的时间
      const startTime = new Date(date)
      startTime.setHours(hours, minutes, seconds, 0)
      
      // 设置结束时间为当天的23:59:59
      const endTime = new Date(date)
      endTime.setHours(23, 59, 59, 999)
      
      // 格式化时间为服务器需要的格式 (YYYY-MM-DDTHH:mm:ss)
      const formatTimeForServer = (date: Date): string => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
      }
      
      const startTimeStr = formatTimeForServer(startTime)
      const endTimeStr = formatTimeForServer(endTime)
      
      console.log('生成回放流地址参数:', {
        camera,
        selectedDate,
        selectedTime,
        startTime: startTimeStr,
        endTime: endTimeStr
      })
      
      // 生成回放token
      const token = generatePlaybackToken({
        deviceId: 0,
        subEquId: camera.subEquId,
        startTime: startTimeStr,
        endTime: endTimeStr
      })
      
      console.log('生成的token:', token)
      
      // 获取回放流地址
      const result = await getPlaybackStreamId(camera.nvrId, token)
      
      if (result.success && result.data && result.data.stream_id) {
        // 构建完整的FLV流地址 - 使用streamPlaybackPort
        const server = streamServer.value.find(s => s.id === camera.nvrId)
        if (server) {
          console.log('服务器信息:', {
            server,
            streamPlaybackPort: streamPlaybackPort.value,
            streamId: result.data.stream_id
          })
          
          // 检查端口是否有效
          let port = streamPlaybackPort.value
          if (!port) {
            console.warn('streamPlaybackPort 为空，使用默认端口 80')
            port = '80'
          }
          const fullStreamUrl = `http://${server.ip}:${port}${result.data.stream_id}`
          
          // 存储流地址
          const cameraKey = `${camera.id}_${selectedDate}_${selectedTime}`
          currentStreamUrls.value.set(cameraKey, fullStreamUrl)
          
          // 保存当前播放的token和streamId用于控制
          currentPlaybackToken.value = token
          currentStreamUrl.value = fullStreamUrl
          
          // 从stream_id中提取streamId（去掉路径前缀和文件扩展名）
          // 例如：从 "/xylive/pb_d0_c35_s20251017T000000Z_e20251017T235959Z/551c5078.flv" 提取 "551c5078"
          const streamIdMatch = result.data.stream_id.match(/\/([^\/]+)\.flv$/)
          if (streamIdMatch) {
            currentStreamId.value = streamIdMatch[1]
            console.log('提取的streamId:', currentStreamId.value)
          } else {
            console.warn('无法从stream_id中提取streamId:', result.data.stream_id)
          }
          
          console.log('获取到流地址:', fullStreamUrl)
          return fullStreamUrl
        } else {
          throw new Error('未找到对应的流媒体服务器')
        }
      } else {
        throw new Error(result.msg || '获取流地址失败')
      }
      
    } catch (error) {
      console.error('生成回放流地址失败:', error)
      const errorMessage = error instanceof Error ? error.message : '获取流地址失败'
      streamError.value = errorMessage
      throw error
    } finally {
      isLoadingStream.value = false
    }
  }
  
  // 批量生成多个摄像头的回放流地址
  const generateBatchPlaybackStreamUrls = async (
    cameras: Device[], 
    selectedDate: string, 
    selectedTime: string
  ): Promise<Map<string, string>> => {
    const streamUrls = new Map<string, string>()
    
    try {
      isLoadingStream.value = true
      streamError.value = ''
      
      // 并发获取所有摄像头的流地址
      const promises = cameras.map(async (camera) => {
        try {
          const streamUrl = await generatePlaybackStreamUrl(camera, selectedDate, selectedTime)
          const cameraKey = `${camera.id}_${selectedDate}_${selectedTime}`
          streamUrls.set(cameraKey, streamUrl)
          return { camera, streamUrl, success: true }
        } catch (error) {
          console.error(`获取摄像头 ${camera.name} 流地址失败:`, error)
          return { camera, streamUrl: '', success: false, error }
        }
      })
      
      const results = await Promise.all(promises)
      
      // 检查是否有失败的请求
      const failedCameras = results.filter(r => !r.success)
      if (failedCameras.length > 0) {
        console.warn('部分摄像头流地址获取失败:', failedCameras)
      }
      
      // 更新store中的流地址
      currentStreamUrls.value = streamUrls
      
      return streamUrls
      
    } catch (error) {
      console.error('批量生成回放流地址失败:', error)
      streamError.value = error instanceof Error ? error.message : '批量获取流地址失败'
      throw error
    } finally {
      isLoadingStream.value = false
    }
  }
  
  // 获取摄像头的流地址
  const getCameraStreamUrl = (cameraId: string, selectedDate: string, selectedTime: string): string => {
    const cameraKey = `${cameraId}_${selectedDate}_${selectedTime}`
    return currentStreamUrls.value.get(cameraKey) || ''
  }
  
  // 清除流地址缓存
  const clearStreamUrls = () => {
    currentStreamUrls.value.clear()
    streamError.value = ''
  }
  

  // 初始化数据
  const initializeData = async () => {
    // 设置默认查询条件（最近24小时）
    const today = new Date()
    const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
    
    queryForm.dateRange = [
      yesterday.toISOString().slice(0, 19).replace('T', ' '),
      today.toISOString().slice(0, 19).replace('T', ' ')
    ]
    
    // 加载菜单树（只加载根节点，不预加载所有摄像头）
    await loadMenuTree()
    
    // 生成录像记录假数据
    generateMockRecords()
  }
  
  return {
    // 状态
    loading,
    selectedRecord,
    playbackPosition,
    isPlaying,
    
    // 目录树相关
    menuTree,
    selectedNode,
    defaultExpandedKeys,
    
    // 摄像头相关
    cameraList,
    selectedCamera,
    folderCameraMap,
    
    // 流媒体服务器相关
    streamServer,
    streamPort,
    streamPlaybackPort,
    
    // 数据
    queryForm,
    pagination,
    cameraPagination,
    recordList,
    playbackRecords,
    
    // 流地址相关状态
    currentStreamUrls,
    isLoadingStream,
    streamError,
    
    // 当前播放控制相关状态
    currentPlaybackToken,
    currentStreamId,
    currentStreamUrl,
    
    // 方法
    loadMenuTree,
    loadCameraList,
    loadCameraRecords,
    selectRecord,
    selectCamera,
    playRecord,
    pausePlayback,
    resumePlayback,
    seekToPosition,
    handleNodeClick,
    resetQuery,
    handlePageChange,
    handlePageSizeChange,
    handleCameraPageChange,
    handleCameraPageSizeChange,
    downloadRecord,
    exportRecords,
    setPlaybackRecords,
    generatePlaybackStreamUrl,
    generateBatchPlaybackStreamUrls,
    getCameraStreamUrl,
    clearStreamUrls,
    initializeData
  }
})
